package com.ysxsoft.wdg.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.umeng.socialize.UMShareAPI;
import com.ysxsoft.wdg.BaseWebViewActivity;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.order.PinOrderDetailActivity;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.bean.AddressBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.StPayResponse;
import com.ysxsoft.wdg.bean.response.WxResponse;
import com.ysxsoft.wdg.bean.zy.ZyConfirmBean;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayPopWindow;
import com.ysxsoft.wdg.pay.PayPopWindow2;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.center_zy.ZyGoodsConfirmActivity;
import com.ysxsoft.wdg.util.JavaInterface;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.SharePopupWindow;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

import static com.tencent.smtt.sdk.WebSettings.LOAD_NO_CACHE;
import static com.ysxsoft.wdg.net.UrlHost.BASE_WEB_URL;

public class THuiWebFragment extends BaseFragment implements ObserverMap.IPageDataChangeObserver, PayResultListener {

    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.content)
    FrameLayout content;
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.parent)
    LinearLayout parent;
    private SharePopupWindow popupWindow;
    private UMShareAPI mShareAPI;
    private PayPopWindow2 payPopWindow;
//    private String mainUrl = "http://zhwdg.sanzhima.cn/index.html#/";
    private String mainUrl = UrlHost.BASE_WEB_URL+"/dist/index.html#/";
    //    private String mainUrl="http://192.168.1.101:8080/#/";
//    private String paySuccessUrl = "http://zhwdg.sanzhima.cn/index.html#/";
    private String paySuccessUrl = UrlHost.BASE_WEB_URL+"/dist/index.html#/";

    //    private String paySuccessUrl = "http://192.168.1.101:8080/#/";
    @Override
    protected int getLayoutId() {
        return R.layout.fm_two_web;
    }

    @Override
    protected void initData() {
        ObserverMap.reg("THuiWebFragment", this);
        initStatusBar(topView, false);
        initWebView(webView);
        webView.loadUrl(mainUrl);
        mShareAPI = UMShareAPI.get(getActivity());
        popupWindow = new SharePopupWindow(getActivity(), mShareAPI);
    }

    private void initWebView(WebView webView) {
        initX5(webView);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                if (url.startsWith("tel:")){
                    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
                    startActivity(intent);
                }
                return true;
            }
        });
        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new JavaInterface(), "aa");
    }

    private void initX5(WebView webView) {
        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
         webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(false);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
    }

    @Override
    public void change() {
    }

    @Override
    public void share(String gid, String url) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                popupWindow.setShareData(getString(R.string.app_name), url, url, "", 0);
                popupWindow.show(parent);
            }
        });
    }

    @Override
    public void share2(String gid, String url) {
        //拼团中  拼团成功 订单详情邀请
    }

    public void goBack(){
        if(webView.canGoBack()){
            webView.goBack();
        }
    }

    public boolean canGoBack(){
        return webView.canGoBack();
    }

    private int type = 1;//1.团购 2砍价 3满减

    @Override
    public void pay(String orderId, String totalMoney, int type, String url) {
        this.type = type;
        this.paySuccessUrl = url;
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                showPayWindow(totalMoney, orderId);
            }
        });
    }

    /**
     * 显示满减
     */
    public void showMPage() {
//        webView.setWebChromeClient(new WebChromeClient());
//        webView.reload();
//        webView.getWebViewClient().shouldOverrideUrlLoading(webView,"http://zhwdg.sanzhima.cn/index.html#/home?index=2");
        Log.e("tag", "重新加载M");
//        webView.clearCache(true);
//        webView.loadUrl("http://www.baidu.com");
        webView.setVisibility(View.GONE);

        content.removeAllViews();
        WebView webView=new WebView(getActivity());
        webView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        content.addView(webView);

        initWebView(webView);
        webView.loadUrl(UrlHost.BASE_URL+"/index.html#/home?index=2");
//        Map<String,String> map=new HashMap<>();
//        map.put("index","2");
//        webView.loadUrl("http://zhwdg.sanzhima.cn/index.html#/home",map);
//        webView.loadUrl("http://www.baidu.com");
    }

    /**
     * 显示团购
     */
    public void showTPage() {
        Log.e("tag", "重新加载T");
        webView.setVisibility(View.GONE);
        content.removeAllViews();
        WebView webView=new WebView(getActivity());
        webView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        content.addView(webView);
        initWebView(webView);
        webView.loadUrl(mainUrl);
    }

    @Override
    public void back() {
        //暂未用到   KanWebViewActivity 返回事件回调
    }

    @Override
    public void toPinOrderDetail(String id) {

    }

    @Override
    public void toKanOrderDetail(String id) {

    }

//    private class WebViewC extends WebViewClient {
//        @Override
//        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//            handler.proceed();
//            super.onReceivedSslError(view, handler, error);
//        }
//    }

    @Override
    protected void setListener() {
        PayListenerUtils.getInstance(getActivity()).addListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ObserverMap.remove("THuiWebFragment");
        PayListenerUtils.getInstance(getActivity()).removeListener(this);
    }

    private void showPayWindow(String payMoney, String orderId) {
        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }
        payPopWindow = new PayPopWindow2(getActivity(), payMoney);
        payPopWindow.show(parent);
        payPopWindow.setOnPayLiatener(new PayPopWindow2.OnPayLiatener() {
            @Override
            public void payType(int payType) {//payment= "3";//支付方式 1=>微信 2=>支付宝 3=>账户余额 4=>积分支付
                AlertUtils.payAlert(getActivity());
                switch (payType) {
                    case 0://余额支付
//                        postPayYue();
                        pay("3", payMoney, orderId);
                        break;
                    case 1://支付宝支付
//                        postPayZfb();
                        pay("1", payMoney, orderId);
                        break;
                    case 2://微信支付
//                        postPayWx();
//                        ToastUtils.showToast("暂未开通");
//                        AlertUtils.dismissAlert();
                        pay("2", payMoney, orderId);
                        break;
                }
            }
        });
    }

    /**
     * 团购满减支付订单
     */
    private void pay(String t, String total, String orderid) {
        OkHttpUtils.post()
                .url(UrlHost.MAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("type", t)//1支付宝2微信3余额支付
                .addParams("total", total)
                .addParams("orderid", orderid)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        AlertUtils.dismissAlert();
//                        ToastUtils.showToast(collectShopResponse.getMs());
                        if ("1".equals(t)) {//支付宝支付
                            postPayZfb(orderid, total);
                        } else if ("2".equals(t)) {//微信支付
                            postPayWx(orderid, total);
                        } else if ("3".equals(t)) {//余额支付
                            webView.loadUrl(paySuccessUrl);
                        }
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 加载网页
     */
    public void reset() {
        if (webView != null) {
            webView.setVisibility(View.VISIBLE);
            webView.loadUrl(mainUrl);
        }
    }

    /**
     * 拼团支付宝支付
     */
    private void postPayZfb(String orderId, String total) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", total)//总价格
                .addParams("type", "1")//1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    StPayResponse stPayResponse = JsonUtils.parseByGson(response, StPayResponse.class);
                    if (stPayResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(stPayResponse.getCode())) {
                        PayUtils.getInstance(mContext).pay(getActivity(), PayUtils.PAY_TYPE_ALI, stPayResponse.getData(), null);
                    } else {
                        ToastUtils.showToast(stPayResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 拼团微信支付
     */
    private void postPayWx(String orderId, String total) {
        OkHttpUtils.post()
                .url(UrlHost.TUAN_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .addParams("total", total)//总价格
                .addParams("type", "2")//1支付宝2微信3余额支付
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    WxResponse wxResponse = JsonUtils.parseByGson(response, WxResponse.class);
                    if (wxResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(wxResponse.getCode())) {
                        WxResponse.DataBean dataBean = wxResponse.getData();

                        WxPayBean bean = new WxPayBean();
                        bean.setAppid(dataBean.getAppid());
                        bean.setNoncestr(dataBean.getNoncestr());
                        bean.setPackageX(dataBean.getPackageX());
                        bean.setPartnerid(dataBean.getPartnerid());
                        bean.setPrepayid(dataBean.getPrepayid());
                        bean.setSign(dataBean.getSign());
                        bean.setTimestamp("" + dataBean.getTimestamp());
                        PayUtils.getInstance(mContext).toWxPay(bean);
                    } else {
                        ToastUtils.showToast(wxResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void onPaySuccess() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast("支付成功!");
                webView.loadUrl(paySuccessUrl);
                Log.e("tag", "aaa:" + paySuccessUrl);
            }
        });
    }

    @Override
    public void onPayError() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast("支付失败!");
            }
        });
    }

    @Override
    public void onPayCancel() {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast("支付取消!");
            }
        });
    }

}
